from django.contrib import localflavor
from countries.models import Country
import os

def scrape_codes(commit=True):
    country_codes = [i['iso'].lower() for i in Country.objects.all().values('iso')]
    
    for code in os.listdir(localflavor.__path__[0]):
        ccode = code
        if code.endswith('_'):
            ccode = code[:-1]
        if ccode in country_codes:
            for name in os.listdir(os.path.join(localflavor.__path__[0], code)):
                if name.startswith(code) and name.endswith('.py') and name.find('postal') == -1:
                    region_choices = list()
                    try:
                        module_name = 'django.contrib.localflavor.' + code
                        name = name[:-3]
                        imp = __import__(module_name, globals(),  locals(), [name], -1)
                        module_name = '.'.join((module_name, name))
                        imp = getattr(imp, name)
                        for item in dir(imp):
                            if item.endswith('_CHOICES') or item.lower() == name:
                                region_choices.append(item)
                    except ImportError:
                        pass
                    else:
                        print module_name, region_choices
                        if commit and len(region_choices) == 1:
                            country = Country.objects.get(iso=ccode.upper())
                            country.region_module = module_name
                            country.region_choices = region_choices[0]
                            country.save()
                            

def disable_non_regions(enable=True):
    for country in Country.objects.all():
        if not country.has_regions():
            country.active = False
            country.save()
        elif enable:
            country.active = True
            country.save()
